<?php
namespace app\index\controller;
use think\Db;
use think\Controller;
use think\Request;
use app\service\AliSmsService;
use think\facade\Env;
use app\service\WxService;
use think\facade\Log;

class Index
{
    /**
     * 新版本,个人历史数据中心 
     */
    public function newUserHistory()
    {
        $params = input('');
        $phone = isset($params['user_phone']) ? $params['user_phone'] : '';
        $pageRows = isset($params['limit']) ? $params['limit'] : 5;
        $title = input('title');
        $res = ['code' => 0, 'data' => [], 'msg' => ''];
        
        if (empty($phone))  exit(json_encode($res, JSON_UNESCAPED_UNICODE));
        # 咨询配置
        $personConf = config('personal_consult_tmpl');

        $condition = [
            'user_phone' => $phone,
            # 股票自动提问的子区间 子栏目不展示
            'pid' => 0
        ];
        
        if($title!=null){
                  $lists = Db::name('new_user_question_history')->where($condition) ->where('person_fix_msg','like','%'.$title.'%')->order('id', 'desc')->paginate($pageRows);
        }else{
                  $lists = Db::name('new_user_question_history')->where($condition)->order('id', 'desc')->paginate($pageRows);
        }
  
        if (!empty($lists->items())) {
            foreach ($lists->items() as $k => $row) {
                if (in_array($row['person_menu_id'], [1, 2, 3, 4])) {
                    $types = $row['person_menu_id'];
                    $itypes = $row['person_menu_item_id'];

                    $msgTmpl = isset($personConf[$types]['items'][$itypes]) ? $personConf[$types]['items'][$itypes] : '';
                    if (empty($msgTmpl)) {
                        $msgTitle = $personConf[$types]['title'];
                    } else {
                        # 如果是, 工作事业选择>>第一条
                        if ($itypes == 4) {
                            $msgTitle = sprintf($msgTmpl, $row['person_fix_msg'], $row['person_job']);
                        } else {
                            $msgTitle = sprintf($msgTmpl, $row['person_fix_msg']);
                        }
                    }
                } else {
                    $msgTitle = $row['person_fix_msg'];
                }
                $esey = $this->getcurl($row['id']);
                $row['esey'] = $esey['data']['easy'];
                $row['answer_id'] = $row['result_id'];
                $row['msg_title'] = $msgTitle;
                $row['history_id'] = $row['id'];
                $row['id'] = date('YmdHis', strtotime($row['add_time'])).$row['id'];
                $row['result_type'] = $row['result_type'];
                $lists[$k] = $row;
            }
        }
        
        $res['data'] = $lists;

        exit(json_encode($res, JSON_UNESCAPED_UNICODE));        
    }
    
    
    
    
    //phpcurl get
    public function getcurl($urltow, $data = '', $method = 'GET')
    {
        $url = 'https://docs.bjwmc.cn/v4/index/getPredict?history_id=' . $urltow;
        // v1/wechat/get_token
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        // curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '') {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }
    
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return json_decode($result,true);
    }
    
    
    /**
     * 最新版本AI预测 
     */
    public function v2latestPersonPredict()
    {
        $params = input('');
        # 需要展示时间节点预测. personal_consult_show
        $personConsultShow = config('personal_consult_show');
        $personConf = config('personal_consult_tmpl');
        # 大类型
        $type  = isset($params['types']) ? $params['types'] : 0;
        # 大栏目下的 子菜单
        $itypes  = isset($params['itypes']) ? $params['itypes'] : 0;
        # 用户填写的信息
        $personMsg = isset($params['person_fix_msg']) ? $params['person_fix_msg'] : '';
        # 职位. 该字段 仅在工作事业栏目有
        $jobTitle = isset($params['person_job']) ? $params['person_job'] : '';
        # 该参数指的是, 当前咨询对应 的 结果ID
        $id = isset($params['id']) ? $params['id'] : 0;
        $res = ['code' => 0, 'data' => [], 'msg' => ''];
        
        if (empty($type) && empty($id))   exit(json_encode($res, JSON_UNESCAPED_UNICODE));
        
        # 没有ID的情况,根据type取出随机数
        if (empty($id)) {
            # 根据 大小菜单, 确认用户提问信息
            $personTpl = isset($personConf[$type]['items'][$itypes]) ? $personConf[$type]['items'][$itypes] : '';
            
            # 如果是 工作事业选择
            if ($itypes == 4) $personTpl = sprintf($personTpl, $jobTitle, $personMsg);
            # 非工作事业选择
            if ($itypes != 4) $personTpl = sprintf($personTpl, $personMsg);   
            
            # 类型不能为空
            if (empty($type)) {
                $res['code'] = 0;
                $res['msg'] = '咨询类型不能为空!';
                exit(json_encode($res, JSON_UNESCAPED_UNICODE));
                exit;
            }
            
            # 新增字段
            $phone = (isset($params['user_phone']) && !empty($params['user_phone'])) ? $params['user_phone'] : '';
            # 手机号不能为空
            if (empty($phone)) {
                $res['code'] = 0;
                $res['msg'] = '手机号为必填参数';
                exit(json_encode($res, JSON_UNESCAPED_UNICODE));
                exit;
            }            
            # 随机取一个. 如果是: 项目预测: 1 + 公关审核
            if ($type == 1 || $type == 4)   $typeIds = Db::name('docs_latest')->field('id')->select();
            # 随机取一个. 如果是: 工作事业选择: 2
            if ($type == 2)   $typeIds = Db::name('docs_works')->field('id')->select();
            # 随机取一个. 如果是: 情感咨询选择: 3
            if ($type == 3)   $typeIds = Db::name('docs_emotion')->field('id')->select();
            
            $typeIdsArr = array_column($typeIds, 'id');
            # 从数组里面随机取出一个
            $key    = array_rand($typeIdsArr);
            $id     = $typeIdsArr[$key];

            $info = [];
            if ($type == 1 || $type == 4)   $info   = Db::name('docs_latest')->field('*')->where(['id' => $id])->find();
            # 随机取一个. 如果是: 工作事业选择: 2
            if ($type == 2)   $info   = Db::name('docs_works')->field('*')->where(['id' => $id])->find();
            # 随机取一个. 如果是: 情感咨询选择: 3
            if ($type == 3)   $info   = Db::name('docs_emotion')->field('*')->where(['id' => $id])->find();            
            # $info   = Db::name('docs_latest')->field('*')->where(['id' => $id])->find();

            $res['code'] = 200;
            # 去除解决方案 字段的空格
            // $info['solution'] =  ltrim($info['solution']);
            # 将当前用户的, 提交记录 存储
            $isShowTimes = in_array($itypes, $personConsultShow['is_show_time_ids']) ? 1 : 0;

            $insertData = [
                'result_id' => $id,
                'user_phone' => $phone,
                'person_menu_id' => $type,
                'person_menu_item_id' => $itypes,
                'person_fix_msg' => $personMsg,
                'person_job' => $jobTitle,
                'is_show_time_res' => $isShowTimes,
                'add_time'=> date('Y-m-d H:i:s', time())
            ];
            $historyId = Db::name('new_user_question_history')->insertGetId($insertData);
            
            $info['is_show_time_res'] = $isShowTimes;
            $info['person_tpl'] = $personTpl;
            $info['history_id'] = $historyId;
            $info['types'] = $type;
            $info['itypes'] = $itypes;
            $res['data'] = $info;

            # Log::info('提问记录::'. json_encode($insertData, JSON_UNESCAPED_UNICODE));
            
            exit(json_encode($res, JSON_UNESCAPED_UNICODE));
        } else {
            # 个人 咨询,历史记录
            $historyId = isset($params['history_id']) ? $params['history_id'] : 0;
            
            if (empty($historyId)) {
                $res['msg'] = '咨询记录ID不能为空!';
                exit(json_encode($res, JSON_UNESCAPED_UNICODE));
            }   
            # 根据 $historyId, 得出它咨询所 得到的答案ID
            $historyInfo = Db::name('new_user_question_history')->field('person_fix_msg,person_job,result_id')->where(['id' => $historyId])->find();
            
            $resultId = $id;
            // $resultId = isset($historyInfo['result_id']) ? $historyInfo['result_id'] : 0;

            if (empty($resultId)) {
                $res['msg'] = '未查询到咨询结果!';
                exit(json_encode($res, JSON_UNESCAPED_UNICODE));                
            }
            # 根据 大小菜单, 确认用户提问信息
            $personTpl = isset($personConf[$type]['items'][$itypes]) ? $personConf[$type]['items'][$itypes] : '';
            # 如果是 工作事业选择
            if ($itypes == 4) $personTpl = sprintf($personTpl, $historyInfo['person_fix_msg'], $historyInfo['person_job']);
            # 非工作事业选择
            if ($itypes != 4) $personTpl = sprintf($personTpl, $historyInfo['person_fix_msg']);
            
            # 随机取一个. 如果是: 项目预测: 1 + 公关审核
            if ($type == 1 || $type == 4) $info = Db::name('docs_latest')->field('*')->where(['id' => $resultId])->find();
            # 随机取一个. 如果是: 工作事业选择: 2
            if ($type == 2)   $info = Db::name('docs_works')->field('*')->where(['id' => $resultId])->find();
            # 随机取一个. 如果是: 情感咨询选择: 3
            if ($type == 3)   $info = Db::name('docs_emotion')->field('*')->where(['id' => $resultId])->find();
                   
            $info['is_show_time_res'] = 1;
            $info['person_tpl'] = $personTpl;
            $res['code'] = 200;
            $res['data'] = $info;

            exit(json_encode($res, JSON_UNESCAPED_UNICODE));            
        }
        exit;        
    }    
    public function latestPersonPredict()
    {
        $params = input('');
        # 需要展示时间节点预测. personal_consult_show
        $personConsultShow = config('personal_consult_show');
        $personConf = config('personal_consult_tmpl');
        # 大类型
        $type  = isset($params['types']) ? $params['types'] : 0;
        # 大栏目下的 子菜单
        $itypes  = isset($params['itypes']) ? $params['itypes'] : 0;
        # 用户填写的信息
        $personMsg = isset($params['person_fix_msg']) ? $params['person_fix_msg'] : '';
        # 职位. 该字段 仅在工作事业栏目有
        $jobTitle = isset($params['person_job']) ? $params['person_job'] : '';
        # 该参数指的是, 当前咨询对应 的 结果ID
        $id = isset($params['id']) ? $params['id'] : 0;
        $res = ['code' => 0, 'data' => [], 'msg' => ''];
        
        if (empty($type) && empty($id))   exit(json_encode($res, JSON_UNESCAPED_UNICODE));
        
        # 没有ID的情况,根据type取出随机数
        if (empty($id)) {
            # 根据 大小菜单, 确认用户提问信息
            $personTpl = isset($personConf[$type]['items'][$itypes]) ? $personConf[$type]['items'][$itypes] : '';
            # 如果是 工作事业选择
            if ($itypes == 4) $personTpl = sprintf($personTpl, $personMsg, $jobTitle);
            # 非工作事业选择
            if ($itypes != 4) $personTpl = sprintf($personTpl, $personMsg);   
            
            # 类型不能为空
            if (empty($type)) {
                $res['code'] = 0;
                $res['msg'] = '咨询类型不能为空!';
                exit(json_encode($res, JSON_UNESCAPED_UNICODE));
                exit;
            }
            # 新增字段
            $phone = (isset($params['user_phone']) && !empty($params['user_phone'])) ? $params['user_phone'] : '';
            # 手机号不能为空
            if (empty($phone)) {
                $res['code'] = 0;
                $res['msg'] = '手机号为必填参数';
                exit(json_encode($res, JSON_UNESCAPED_UNICODE));
                exit;
            }            
            # 随机取一个. 如果是: 项目预测: 1 + 公关审核
            if ($type == 1 || $type == 4)   $typeIds = Db::name('docs_latest')->field('id')->select();
            # 随机取一个. 如果是: 工作事业选择: 2
            if ($type == 2)   $typeIds = Db::name('docs_works')->field('id')->select();
            # 随机取一个. 如果是: 情感咨询选择: 3
            if ($type == 3)   $typeIds = Db::name('docs_emotion')->field('id')->select();
            
            $typeIdsArr = array_column($typeIds, 'id');
            # 从数组里面随机取出一个
            $key    = array_rand($typeIdsArr);
            $id     = $typeIdsArr[$key];

            $info = [];
            $info = Db::name('docs_latest')->field('*')->where(['id' => $id])->find();

            $res['code'] = 200;
            # 去除解决方案 字段的空格
            // $info['solution'] =  ltrim($info['solution']);
            # 将当前用户的, 提交记录 存储
            $isShowTimes = in_array($itypes, $personConsultShow['is_show_time_ids']) ? 1 : 0;

            $insertData = [
                'result_id' => $id,
                'user_phone' => $phone,
                'person_menu_id' => $type,
                'person_menu_item_id' => $itypes,
                'person_fix_msg' => $personMsg,
                'person_job' => $jobTitle,
                'is_show_time_res' => $isShowTimes,
                'add_time'=> date('Y-m-d H:i:s', time())
            ];
            Db::name('new_user_question_history')->insert($insertData);
            
            $info['is_show_time_res'] = $isShowTimes;
            $info['person_tpl'] = $personTpl;
            $res['data'] = $info;
            # Log::info('提问记录::'. json_encode($insertData, JSON_UNESCAPED_UNICODE));
            
            exit(json_encode($res, JSON_UNESCAPED_UNICODE));
        } else {
            # 随机取一个. 如果是: 项目预测: 1 + 公关审核
            $info = Db::name('docs_latest')->field('*')->where(['id' => $id])->find();
            $info['is_show_time_res'] = 1;
            $res['code'] = 200;
            $res['data'] = $info;

            exit(json_encode($res, JSON_UNESCAPED_UNICODE));            
        }
        exit;        
    }    
   
    /**
     * 新版本. 个人用户,预测结果 
     */
    public function newPersonPredict()
    {
        $params = input('');
        # 需要展示时间节点预测. personal_consult_show
        $personConsultShow = config('personal_consult_show');
        
        $personConf = config('personal_consult_tmpl');
        # 大类型
        $type  = isset($params['types']) ? $params['types'] : 0;
        # 大栏目下的 子菜单
        $itypes  = isset($params['itypes']) ? $params['itypes'] : 0;
        # 用户填写的信息
        $personMsg = isset($params['person_fix_msg']) ? $params['person_fix_msg'] : '';
        # 职位. 该字段 仅在工作事业栏目有
        $jobTitle = isset($params['person_job']) ? $params['person_job'] : '';
        
        $id = isset($params['id']) ? $params['id'] : 0;
        $res = ['code' => 0, 'data' => [], 'msg' => ''];
        
        if (empty($type) && empty($id))   exit(json_encode($res));
        # 没有ID的情况,根据type取出随机数
        if (empty($id)) {
            # 类型不能为空
            if (empty($type)) {
                $res['code'] = 0;
                $res['msg'] = '咨询类型不能为空!';
                exit;
            }
            # 新增字段
            $phone = (isset($params['user_phone']) && !empty($params['user_phone'])) ? $params['user_phone'] : '';
            # 手机号不能为空
            if (empty($phone)) {
                $res['code'] = 0;
                $res['msg'] = '手机号为必填参数';
                exit;
            }            
            # 随机取一个
            // $typeIds = Db::name('docs_new')->field('id')->select();
            $typeIds = Db::name('docs_new')->field('id')->select();
            
            $typeIdsArr = array_column($typeIds, 'id');
            # 从数组里面随机取出一个
            $key    = array_rand($typeIdsArr);
            $id     = $typeIdsArr[$key];
            $info   = Db::name('docs_new')->field('*')->where(['id' => $id])->find();

            $res['code'] = 200;
            # 去除解决方案 字段的空格
            // $info['solution'] =  ltrim($info['solution']);
            # 将当前用户的, 提交记录 存储
            $isShowTimes = in_array($itypes, $personConsultShow['is_show_time_ids']) ? 1 : 0;

            $insertData = [
                'result_id' => $id,
                'user_phone' => $phone,
                'person_menu_id' => $type,
                'person_menu_item_id' => $itypes,
                'person_fix_msg' => $personMsg,
                'person_job' => $jobTitle,
                'is_show_time_res' => $isShowTimes,
                'add_time'=> date('Y-m-d H:i:s', time())
            ];
            Db::name('new_user_question_history')->insert($insertData);
            $info['is_show_time_res'] = $isShowTimes;
            $res['data'] = $info;
            # Log::info('提问记录::'. json_encode($insertData, JSON_UNESCAPED_UNICODE));
            
            exit(json_encode($res, JSON_UNESCAPED_UNICODE));
        } else {
            # docs_latest
            $info = Db::name('docs_new')->field('*')->where(['id' => $id])->find();
            // $info['solution'] =  ltrim($info['solution']);            
            $res['code'] = 200;
            $res['data'] = $info;

            exit(json_encode($res, JSON_UNESCAPED_UNICODE));            
        }
        exit;        
    }
    /**
     * 获取用户每天首次打开app的 IP 
     */
    public function logUserIp() {
        $params = input('');
        $phone = (isset($params['user_phone']) && !empty($params['user_phone'])) ? $params['user_phone'] : '';

        $res = ['code' => 0, 'data' => [], 'msg' => ''];        
        # 手机号不能为空
        if (empty($phone) || $phone = 'undefined') {
            $res['code'] = 1002;
            $res['msg'] = '手机号为必填参数';
            echo json_encode($res, JSON_UNESCAPED_UNICODE);
            exit;
        }
        $userIp = $_SERVER['REMOTE_ADDR'];
        $insertData = [
            'user_phone' => $phone,
            'user_ip' => $userIp,
            'login_time' => date('Y-m-d H:i:s')
        ];
        $insertRes = Db::name('userip_logs')->insert($insertData);
        
        if (!$insertRes) {
            $res['code'] = 1003;
            $res['msg'] = '上报IP失败';
            echo json_encode($res, JSON_UNESCAPED_UNICODE);
            exit;            
        }
        
        echo json_encode($res, JSON_UNESCAPED_UNICODE);
    }
    /**
     * 用户登录协议 
     */
    public function getProtocal()
    {
        $protacalData = config('user_login_protocal');
        $res = [
            'code' => 0,
            'data' => [],
            'msg' => ''    
        ];
        $res['data'] = $protacalData;
        
        echo json_encode($res, JSON_UNESCAPED_UNICODE);
        exit;
    }
    /**
     * 展示新版本数据
     */
    public function getNewindex()
    {
        $params = input('');
        $type  = isset($params['types']) ? $params['types'] : 3;
        $id = isset($params['id']) ? $params['id'] : 0;
        
        $presenSituation = (isset($params['presen_situation']) && !empty($params['presen_situation']) && $params['presen_situation'] != 'undefined') ? $params['presen_situation'] : '未选择';
        $xinTai = (isset($params['xintai']) && !empty($params['xintai']) && $params['xintai'] != 'undefined') ? $params['xintai'] : '未选择';
        $isActive = (isset($params['is_active']) && !empty($params['is_active']) && $params['is_active'] != 'undefined') ? $params['is_active'] : '未选择';
        $isHelp = (isset($params['is_help']) && !empty($params['is_help']) && $params['is_help'] != 'undefined') ? $params['is_help'] : '未选择';
        # 新需求 都改为3
        $type = 3;
        $res = ['code' => 0, 'data' => [], 'msg' => ''];
        
        if (empty($type) && empty($id))   exit(json_encode($res));
        # 没有ID的情况,根据type取出随机数
        if (empty($id)) {
            # 新增字段
            $phone = (isset($params['user_phone']) && !empty($params['user_phone'])) ? $params['user_phone'] : '';
            # 手机号不能为空
            
            if (empty($phone)) {
                $res['code'] = 0;
                $res['msg'] = '手机号为必填参数';
                exit;
            }            
            # 如果 type=3, 则不区分类型,随机取一个
            if ($type == 3) {
                $typeIds = Db::name('docs_new')->field('id')->select();
            } else {
                $typeIds = Db::name('docs_new')->field('id')->where(['types' => $type])->select();
            }
            
            $typeIdsArr = array_column($typeIds, 'id');
            # 从数组里面随机取出一个
            $key    = array_rand($typeIdsArr);
            $id     = $typeIdsArr[$key];
            $info   = Db::name('docs_new')->field('*')->where(['id' => $id])->find();

            $res['code'] = 200;
            $res['data'] = $info;
            # 去除解决方案 字段的空格
            $info['solution'] =  ltrim($info['solution']);
            # 将当前用户的, 提交记录 存储
            $insertData = [
                'answer_id' => $id,
                'user_phone' => $phone,
                'presen_situation' => $presenSituation,
                'xintai' => $xinTai,
                'is_active' => $isActive,
                'is_help' => $isHelp,
                'add_time'=> date('Y-m-d H:i:s', time())
            ];
            Db::name('user_question_history')->insert($insertData);
            Log::info('提问记录::'. json_encode($insertData, JSON_UNESCAPED_UNICODE));
            
            exit(json_encode($res, JSON_UNESCAPED_UNICODE));
        } else {
            $info = Db::name('docs_new')->field('*')->where(['id' => $id])->find();
            $info['solution'] =  ltrim($info['solution']);            
            $res['code'] = 200;
            $res['data'] = $info;

            exit(json_encode($res, JSON_UNESCAPED_UNICODE));            
        }
        exit;
    }    
    /**
     * 展示数据
     */
    public function index()
    {
        $params = input('');
        $type  = isset($params['types']) ? $params['types'] : 3;
        $id     = isset($params['id']) ? $params['id'] : 0;
        
        $presenSituation = (isset($params['presen_situation']) && !empty($params['presen_situation']) && $params['presen_situation'] != 'undefined') ? $params['presen_situation'] : '未选择';
        $xinTai = (isset($params['xintai']) && !empty($params['xintai']) && $params['xintai'] != 'undefined') ? $params['xintai'] : '未选择';
        $isActive = (isset($params['is_active']) && !empty($params['is_active']) && $params['is_active'] != 'undefined') ? $params['is_active'] : '未选择';
        $isHelp = (isset($params['is_help']) && !empty($params['is_help']) && $params['is_help'] != 'undefined') ? $params['is_help'] : '未选择';
        # 新需求 都改为3
        $type = 3;
        
        if (empty($type) && empty($id))   exit(json_encode($res));
        # 没有ID的情况,根据type取出随机数
        if (empty($id)) {
            # 新增字段
            $phone = (isset($params['user_phone']) && !empty($params['user_phone'])) ? $params['user_phone'] : '';
            # 手机号不能为空
            $res = ['code' => 0, 'data' => [], 'msg' => ''];
            if (empty($phone)) {
                $res['code'] = 0;
                $res['msg'] = '手机号为必填参数';
                exit;
            }            
            # 如果 type=3, 则不区分类型,随机取一个
            if ($type == 3) {
                $typeIds = Db::name('docs')->field('id')->select();
            } else {
                $typeIds = Db::name('docs')->field('id')->where(['types' => $type])->select();
            }
            
            $typeIdsArr = array_column($typeIds, 'id');
            # 从数组里面随机取出一个
            $key    = array_rand($typeIdsArr);
            $id     = $typeIdsArr[$key];
            $info   = Db::name('docs')->field('*')->where(['id' => $id])->find();

            $res['code'] = 200;
            $res['data'] = $info;
            # 去除解决方案 字段的空格
            $info['solution'] =  ltrim($info['solution']);
            # 将当前用户的, 提交记录 存储
            $insertData = [
                'answer_id' => $id,
                'user_phone' => $phone,
                'presen_situation' => $presenSituation,
                'xintai' => $xinTai,
                'is_active' => $isActive,
                'is_help' => $isHelp,
                'add_time'=> date('Y-m-d H:i:s', time())
            ];
            Db::name('user_question_history')->insert($insertData);
            Log::info('提问记录::'. json_encode($insertData, JSON_UNESCAPED_UNICODE));
            
            exit(json_encode($res));
        } else {
            $info = Db::name('docs')->field('*')->where(['id' => $id])->find();
            $info['solution'] =  ltrim($info['solution']);            
            $res['code'] = 200;
            $res['data'] = $info;

            exit(json_encode($res));            
        }
        exit;
    }
    /**
     * 获取用户提问 历史记录
     */
    public function getUserHistory()
    {
        $params = input('');
        $phone = isset($params['user_phone']) ? $params['user_phone'] : '';
        $pageRows = isset($params['limit']) ? $params['limit'] : 5;
        
        $res = ['code' => 0, 'data' => [], 'msg' => ''];
        
        if (empty($phone))  exit(json_encode($res));
        $condition = [
            'user_phone' => $phone     
        ];
        $lists = Db::name('user_question_history')->where($condition)->order('id', 'desc')->paginate($pageRows);
        
        if (!empty($lists->items())) {
            foreach ($lists->items() as $k => $row) {
                $row['id'] = date('YmdHis', strtotime($row['add_time'])).$row['id'];
                $lists[$k] = $row;
            }                        
        }
        $res['data'] = $lists;

        exit(json_encode($res, JSON_UNESCAPED_UNICODE));
    }
    /**
     * 获取单选item 
     */
    public function getChoices(Request $req)
    {
        $result = [
            'code' => 0,
            'msg'  => '',
            'data' => [
                'xintai' => [],
                'initiative' => [],
                'is_help' => []
            ]
        ];
        $lists = Db::name('choices')->select();
        
        if (!empty($lists))
        {
            foreach ($lists as $k => $item) {
                if ($item['types'] == 1) array_push($result['data']['xintai'], $item);
                if ($item['types'] == 2) array_push($result['data']['initiative'], $item);
                if ($item['types'] == 3) array_push($result['data']['is_help'], $item);
            }
        }
        
        echo json_encode($result, true);
        exit;
    }
    /**
     * 获取版本号 
     */
    public function getVer()
    {
        # 下载地址，版本号，版本名，描述
        $result = [
            'code' => 0,
            'msg'  => '',
            'data' => [
                'version' => '622',
                'version_name' => '6.2.2',
                'download_url' => 'http://www.bjwmc.cn/ai-v6.2.2-release.apk',
                'version_desc' => '1: 更新部分UI及功能优化...'
            ]
        ];
        
        echo json_encode($result);
        exit;
    }
    /**
     * 小程序通过 code换取openid 
     */
    public function getOpenid(Request $req)
    {
        $result = [
            'code' => 0,
            'msg'  => '',
            'data' => []
        ];        
        $code = $req->post('js_code', '');
        
        if (empty($code)) {
            $result['code'] = 1;
            $result['msg']  = 'code参数为必填项!';
            
            echo json_encode($result);
            exit;              
        }
        
        $wxServiceObj = new WxService();
        $res = $wxServiceObj->getOpenidByCode($code);
        
        if (isset($res['errcode'])) {
            $result['code'] = $res['errcode'];
            $result['msg']  = $res['errmsg'];
            
            echo json_encode($result);
            exit;              
        }
        
        $result['data'] = $res;
        echo json_encode($result);
        exit;          
    }
    /**
     * 获取小程序手机号
     */
    public function getUserWxPhone(Request $req)
    {
        $result = [
            'code' => 0,
            'msg'  => '',
            'data' => []
        ];  
        
        # $iv = $req->post('iv', '');
        # $sessionKey = $req->post('session_key', '');
        # $encryptedData = $req->post('encryptedData', '');
        $getPhoneCode  = $req->post('code', '');
        
        if (empty($getPhoneCode)) {
            $result['code'] = 1;
            $result['msg']  = '请求参数不完整!';
            
            echo json_encode($result);
            exit;              
        }

        $wxServiceObj = new WxService();
        $reqData  = [
            'code' => $getPhoneCode  
        ];
        $phoneRes = $wxServiceObj->getMiniPhone($reqData);
        
        if ($phoneRes['errcode'] > 0) {
            $result['code'] = $phoneRes['errcode'];
            $result['msg']  = $phoneRes['errmsg'];
            
            echo json_encode($result);
            exit;              
        }

        $result['data'] = $phoneRes['phone_info'];
        echo json_encode($result);
        exit;           
    }
    /**
     * 根据参数获取sign 
     */
    public function getSign($arr)
    {
        # API访问时间是3分钟内有效
        if (time() - $arr['timestamp'] > 1800)  return false;
        # 去除sign参数
        $signParam = $arr['sign'];
        unset($arr['sign']);
        
        ksort($arr);
        //按照E代驾Api拼接参数
        $str    = http_build_query($arr);
        $str_1  = str_replace('=', '', $str);
        $str_2  = str_replace('&', '', $str_1);

        //拼接secret，再进行md5，再取前30位
        $secret = Env::get('app.signAppSecret').$str_2.Env::get('app.signAppSecret');
        $sign   = substr(md5($secret), 0,30);

        if ($signParam == $sign) return true;
        
        return false;
    }
    
    /**
     * 发送短信验证码 
     */
    public function sendSmsCode(Request $req)
    {
        $result = [
            'code' => 0,
            'msg'  => '',
            'data' => [
                'res' => ''    
            ]
        ];
        
        $phone = $req->post('phone', '');
        
        if (empty($phone) || !checkPhone($phone))
        {
            $result['code'] = 1;
            $result['msg']  = '手机号格式不正确!';
            
            echo json_encode($result);
            exit;
        }
        # sign验签
        $params = input('');
        $checkRes = $this->getSign($params);
        
        if (!$checkRes) {
            $result['code'] = 1;
            $result['msg']  = '签名验证错误!';
            
            echo json_encode($result);
            exit;            
        }
        
        $aliSmsConfig = config('app.ali_sms');
        $code = rand(100000, 999999);
        $args = [
            'phone' => $phone,
            'template'  => $aliSmsConfig['regCodeTpl'],
            'params'    => '{"code":"'.$code.'"}'
        ];
        $res = AliSmsService::main($args); 
        cache($phone, $code);
        # 检测当前手机号是否存在
        $userId = Db::name('member')->where(['phone' => $phone])->column('id');

        $result['msg']  = 'success';
        $result['data']['is_show'] = empty($userId) ? 1 : 0;

        echo json_encode($result);
        exit;
    }
    /**
     * 查询当前用户是否使用超过限制
     * 免费次数为
     */
    public function checkUserIsAllowed(Request $req)
    {
        $result = [
            'code' => 0,
            'msg'  => '',
            'data' => 0
        ];        
        $freeNum = env('app.freeNum', 0);
        # type: 判断是否是小程序. 小程序传openid. 客户端: 使用IP
        $types = $req->post('types', 'app');
        $openid = $req->post('openid', '');
        $visitIp= $req->post('ip', $req->server('REMOTE_ADDR'));
        # 默认不需要注册
        $allowFlag = 1;

        if ($types == 'mini')
        {
            if (empty($openid)) 
            {
                $result['code'] = 1;
                $result['msg']  = '微信用户标识为必传项!';
                
                echo json_encode($result);
                exit;            
            }
            # 注册用户,免费使用
            $userId = Db::name('member')->where(['openid' => $openid])->column('id');

            # 非注册用户只有免费次数
            if (empty($userId)) {
                $nums = Db::name('member_logs')->where(['visit_openid' => $openid])->count('*');

                if ($nums >= $freeNum) $allowFlag = 0;
            }
        } else {
            $nums = Db::name('member_logs')->where(['visit_ip' => $visitIp])->count('*');
            dump($nums);
            if ($nums >= $freeNum) $allowFlag = 0;
        }

        # 通过则加入数据
        $data = [
            'visit_ip' => $visitIp,
            'visit_openid' => $openid,
            'create_time'  => time()
        ];
        Db::name('member_logs')->insert($data);
        
        $result['data']  = $allowFlag;
        
        echo json_encode($result);
        exit;         
    }
    /**
     * 执行注册 
     */
    public function doReg(Request $req)
    {
        $result = [
            'code' => 0,
            'msg'  => '',
            'data' => [
                'res' => ''
            ]
        ];
        # type: 判断是否是小程序
        $types = $req->post('types', 'app');
        $uid = $req->post('uid', 0);
        $cid3 = $req->post('cid3', 0);
        $phone = $req->post('phone', '');
        $smsCode = $req->post('smsCode', '');
        $openid  = $req->post('openid', '');
        $sex = $req->post('sex', '');
        $birth = $req->post('birth', '');
        $agentId = $req->post('agentId', 0);
        $hasTizhiQualify = $req->post('hasTizhiQualify', 0);
        
        # 增加一个测试账号
        if ($phone == '18611111111' && $smsCode == '888888') {
            $info = Db::name('member')->field('phone,openid,create_time')->where(['phone' => $phone])->find();
            
            if (!empty($info)) {
                $result['data'] = $info;
                
                echo json_encode($result);
                exit;             
            }            
        }
        # 非小程序, 必须对比验证码 
        if ($types != 'mini') {
            if (empty($smsCode)) 
            {
                $result['code'] = 1;
                $result['msg']  = '注册参数不完整!';
                
                echo json_encode($result);
                exit;            
            }
            $cacheCode = cache($phone);
    
            if ($smsCode != $cacheCode)
            {
                $result['code'] = 1;
                $result['msg']  = '短信验证码不正确!';
                
                echo json_encode($result);
                exit;            
            }             
        }
        # 检验手机号
        if (empty($phone) || !checkPhone($phone))
        {
            $result['code'] = 1;
            $result['msg']  = '手机号格式不正确!';
            
            echo json_encode($result);
            exit;
        }
        # TODO:: 小程序必须传 openid
        if ($types == 'mini' && empty($openid)) {
            $result['code'] = 1;
            $result['msg']  = '小程序用户唯一标识,必传!';
            
            echo json_encode($result);
            exit;            
        }
        # 检测当前手机号是否注册
        $info = Db::name('member')->field('phone,openid,agent_id,create_time')->where(['phone' => $phone])->find();
        $result['msg']  = '登录成功!';
        # 如果带有 体质查询,体验标志
        if ($hasTizhiQualify == 1 && time() > Env::get('app.tizhiPresentTimeEnd', 0)) $result['msg'] = 'over';
        if ($hasTizhiQualify == 1 && time() < Env::get('app.tizhiPresentTimeEnd')) $result['msg'] = 'ok';
        
        if (!empty($info)) {
            # 未绑定代理上的,可以绑定一次
            if ($info['agent_id'] == 0 && $agentId > 0 && $info['phone'] != $phone) Db::name('member')->where(['phone' => $phone])->update(['agent_id' => $agentId]);
            $result['data'] = $info;
            
            echo json_encode($result);
            exit;             
        }
        $cid3Map =config('app.cid3_map');
        
        $vip = !empty($cid3) ? $cid3Map[$cid3] : 0;

        $vipKey = isset($vip['once_field']) ? $vip['once_field'] : 0;
        # 新增用户免费次卡数量
        $addData = [
            'phone' => $phone,
            'openid'=> $openid,
            'sex' => $sex,
            'birth' => $birth,
            'create_time' => time(),
            'uid'=>$uid
        ];
        # 一个用户只能捆绑一个代理商. 只有没有代理商的,才需要绑定
        if ($info['agent_id'] == 0) $addData['agent_id'] = $agentId;        
        //邀新用户奖励 1次免费
        if($uid && $cid3){
            Db::name('member')->where('id',$uid)->setInc($vipKey);
        }
      
        $res = Db::name('member')->insert($addData);
        
        if (!$res) {
            $result['code'] = 1;
            $result['msg']  = '登录失败!';
            
            echo json_encode($result);
            exit;              
        }
        $result['data'] = $addData;
        
        echo json_encode($result);
    }
    /**
     * 新版本数据导入(项目预测+公关审核)
     */
    public function newAddRow()
    {
        // ["111115(1)","需要靠另一方或外界环境/市场的情况下","以20年为时间单位的事件:","描述...","以年为时间单位的事件:","描述...","以月为时间单位的事件:","描述...","以日为时间单位的事件:","描述...","该事件是否可以获得利益:","结束后复盘成本核算不得利益.","客方对主方想法:","潜伏状态.","咨询人推进意愿:","当事人当前有推进意愿,双方关系对等,极端问题可行.\n所处环境中男性或者主动处事人居多.","该事件总体推进难易度:","较费时间和精力.","客方心态:","另一方或者外界环境/市场占主动但无方向,但交流有进展","咨询人心态:","当事人主动但无方向.\n当事人和另一方性别男或者性格偏男性.","客方心理活动:","另一方或者外界环境/市场想反复推进去做该事情,但做不到反复推进该事件.","咨询人心理活动:","当事人想反复推进去做该事情.","解决方案:","需要反复推进去做该事情\n另一方或外界环境/市场内部有不满"]        
        $arr = [];

        if (!empty($arr)) {
            foreach ($arr as $k => $row) {
                $res = [];
                $res['num_sn']  = isset($row[0]) ? $row[0] : '000';
                $res['preface']  = '需要靠另一方或外界环境/市场的情况下';
                $res['twenty_years_predict']  = isset($row[2]) ? $row[2] : '暂无数据';
                $res['years_predict']  = isset($row[4]) ? $row[4] : '暂无数据';
                $res['month_predict']  = isset($row[6]) ? $row[6] : '暂无数据';
                $res['day_predict']  = isset($row[8]) ? $row[8] : '暂无数据';
                
                $res['ds_twenty_years_predict']  = isset($row[10]) ? $row[10] : '暂无数据';
                $res['ds_years_predict']  = isset($row[12]) ? $row[12] : '暂无数据';
                $res['ds_month_predict']  = isset($row[14]) ? $row[14] : '暂无数据';
                $res['ds_day_predict']  = isset($row[16]) ? $row[16] : '暂无数据';                
                
                $res['is_get_profit']  = isset($row[18]) ? $row[18] : '暂无-事件是否可得利益';
                
                $res['ke_zhu_idea']  = isset($row[20]) ? $row[20] : '暂无-咨询人推进意愿';
                $res['zixun_wants'] = isset($row[22]) ? $row[22] : '暂无-客方对主方想法';
                # 咨询人推进意愿
                $res['things_degree'] = isset($row[24]) ? $row[24] : '暂无-事件总体推进难易程度';
                # 客方心态
                $res['customer_xintai'] = isset($row[26]) ? $row[26] : '暂无-客方心态';
                # 咨询人心态
                $res['zixun_xintai']    = isset($row[28]) ? $row[28] : '暂无-咨询人心态';
                # 客方心理活动
                $res['customer_xinli'] = isset($row[30]) ? $row[30] : '暂无-客方心里活动';
                # 咨询人心理活动
                $res['zixun_xinli']    = isset($row[32]) ? $row[32] : '暂无-咨询人心理活动';
                # 解决方案
                $res['solution']    = isset($row[34]) ? $row[34] : '暂无-解决方案';
                
                # 只需要改这里: 1,2,3
                $res['types']   = 2;
                # 是否是good. 1-是,2-否
                $res['is_good'] = 2;
                
                $res['add_time'] = date('Y-m-d H:i:s', time());
                # good文档
                // dump($res);die();
                Db::name('docs_latest_copy')->insert($res);                
                // $titleArr = explode(' ',$row[0]);
                // $res = [];
                // $res['num_sn']  = isset($row[0]) ? $row[0] : '000';
                // $res['predict']  = isset($row[1]) ? $row[1] : '暂无数据';
                // $res['is_get_profit']  = isset($row[3]) ? $row[3] : '暂无-事件是否可得利益';
                
                // $res['ke_zhu_idea'] = isset($row[5]) ? $row[5] : '暂无-客方对主方想法';
                // $res['things_degree']  = isset($row[9]) ? $row[9] : '暂无-咨询人推进意愿';
                // # 咨询人推进意愿
                // $res['zixun_wants'] = isset($row[7]) ? $row[7] : '暂无-事件总体推进难易程度';
                // # 客方心态
                // $res['customer_xintai'] = isset($row[11]) ? $row[11] : '暂无-客方心态';
                // # 咨询人心态
                // $res['zixun_xintai']    = isset($row[13]) ? $row[13] : '暂无-咨询人心态';
                // # 客方心理活动
                // $res['customer_xinli'] = isset($row[15]) ? $row[15] : '暂无-客方心里活动';
                // # 咨询人心理活动
                // $res['zixun_xinli']    = isset($row[17]) ? $row[17] : '暂无-咨询人心理活动';
                // # 解决方案
                // $res['solution']    = isset($row[19]) ? $row[19] : '暂无-解决方案';
                
                // # 只需要改这里: 1,2,3
                // $res['types']   = 2;
                // # 是否是good. 1-是,2-否
                // $res['is_good'] = 2;
                
                // $res['add_time'] = date('Y-m-d H:i:s', time());
                // # good文档
                // // dump($res);die();
                // Db::name('docs_new_copy')->insert($res); 
                
            }            
        }

        exit('success');
    }
    /**
     * 导入数据(工作事业选择)
     */
    public function addWorksRow()
    {
        # ["111115(1) ","以年为时间单位的进展:","以年为时间单位的进展...","以月为时间单位的进展:","以月为时间单位的进展...","以年为时间单位的进展:","公司角度,以年为时间单位的进展...","以月为时间单位的进展:","公司角度,以月为时间单位的进展...","我在该公司是否可以获得利益:","结束后复盘成本核算不得利益.","该公司对我的想法:","潜伏状态.","我在该公司的工作意愿:","我当前有推进意愿,双方关系对等,极端问题可行.\n所处环境中男性或者主动处事人居多.","我在该公司工作推进难易度:","较费时间和精力.","该公司的心态:","该公司占主动但无方向,但交流有进展","我的心态:","我主动但无方向.\n我和该公司性别男或者性格偏男性.","该公司此时的心理活动:","该公司想反复推进去做该事情,但做不到坚持反复推进该事件.","我此时的心理活动:","我想反复推进去做该事情.","该公司希望我:","希望反复推进去做该事情\n该公司内部有不满"]
        $arr = [];

        if (!empty($arr)) {
            foreach ($arr as $k => $row) {
                $res = [];
                $res['num_sn']  = isset($row[0]) ? $row[0] : '000';
                $res['me_role_years_desc']  = isset($row[2]) ? $row[2] : '暂无数据';
                $res['me_role_month_desc']  = isset($row[4]) ? $row[4] : '暂无数据';
                $res['cm_role_years_desc'] = isset($row[6]) ? $row[6] : '暂无数据';
                $res['cm_role_month_desc']  = isset($row[8]) ? $row[8] : '暂无数据';
                # 我在该公司,是否可以获得利益
                $res['me_is_getprofit'] = isset($row[10]) ? $row[10] : '暂无数据';
                # 该公司对我的想法
                $res['cm_idea_for_me'] = isset($row[12]) ? $row[12] : '暂无数据';
                # 我在该公司的⼯作意愿
                $res['me_work_idea']    = isset($row[14]) ? $row[14] : '暂无数据';
                $res['me_work_things_degree']    = isset($row[16]) ? $row[16] : '暂无数据';
                $res['cm_xintai']    = isset($row[18]) ? $row[18] : '暂无数据';
                $res['me_xintai']    = isset($row[20]) ? $row[20] : '暂无数据';
                $res['cm_xinli']    = isset($row[22]) ? $row[22] : '暂无数据';
                $res['me_xinli']    = isset($row[24]) ? $row[24] : '暂无数据';
                $res['cm_hope_me']    = isset($row[26]) ? $row[26] : '暂无数据';                
                
                # 只需要改这里: 1,2,3
                $res['types']   = 2;
                # 是否是good. 1-是,2-否
                $res['is_good'] = 2;
                
                Db::name('docs_works_copy')->insert($res);
            }            
        }

        exit('success');
    }
    /**
     * 导入数据(情感选择)
     */
    public function addEmotionRow()
    {
        // ["111115(1) ","ta的开心年:","ta的开心年...","ta的开心月:","ta的开心月...","ta的开心日:","ta的开心日...","我的开心年:","我的开心年...","我的开心月:","我的开心月...","我的开心日:","我的开心日...","ta对我的想法:","潜伏状态.","我对于该感情的推进意愿:","我当前有推进意愿,双方关系对等,极端问题可行.\n所处环境中男性或者主动处事人居多.","我在该感情里推进的难易度:","较费时间和精力.","ta的心态:","ta占主动但无方向,但交流开心","我的心态:","我主动但无方向.\n我和ta性别男或者性格偏男性.","ta对于该感情此时的想法:","ta想反复推进感情关系,但做不到反复推进感情关系.","我对于该感情此时的想法:","我想反复推进感情关系.","ta希望我:","希望反复推进感情关系\nta朋友家人有不满"]        
        $arr = [];

        if (!empty($arr)) {
            foreach ($arr as $k => $row) {
                $res = [];
                $res['num_sn']  = isset($row[0]) ? $row[0] : '000';
                $res['ta_years_desc']  = isset($row[2]) ? $row[2] : '暂无数据';
                $res['ta_month_desc']  = isset($row[4]) ? $row[4] : '暂无数据';
                $res['ta_day_desc'] = isset($row[6]) ? $row[6] : '暂无数据';
                $res['me_years_desc']  = isset($row[8]) ? $row[8] : '暂无数据';
                $res['me_month_desc']  = isset($row[10]) ? $row[10] : '暂无数据';
                $res['me_day_desc'] = isset($row[12]) ? $row[12] : '暂无数据';                
                # ta对我的想法
                $res['ta_wants'] = isset($row[14]) ? $row[14] : '暂无数据';
                # 我对于该感情的推进意愿
                $res['me_tuijin'] = isset($row[16]) ? $row[16] : '暂无数据';
                # 我在该感情里推进的难易度
                $res['me_tuijin_degree']    = isset($row[18]) ? $row[18] : '暂无数据';
                
                $res['ta_xintai']    = isset($row[20]) ? $row[20] : '暂无数据';
                $res['me_xintai']    = isset($row[22]) ? $row[22] : '暂无数据';
                $res['ta_xinli']    = isset($row[24]) ? $row[24] : '暂无数据';
                $res['me_xinli']    = isset($row[26]) ? $row[26] : '暂无数据';
                $res['ta_hope_me']    = isset($row[28]) ? $row[28] : '暂无数据';                
                
                # 只需要改这里: 1,2,3
                $res['types']   = 2;
                # 是否是good. 1-是,2-否
                $res['is_good'] = 2;
                
                Db::name('docs_emotion_copy')->insert($res);
            }            
        }

        exit('success');
    }     
    /**
     * 导入数据
     */
    public function addRow()
    {
        $arr = [];

        if (!empty($arr)) {
            foreach ($arr as $k => $row) {
                $titleArr = explode(' ',$row[0]);
                $res = [];
                $res['num_sn']  = isset($titleArr[0]) ? $titleArr[0] : '000';
                $res['result']  = isset($titleArr[1]) ? $titleArr[1] : '暂无数据';
                $res['tuijin']  = isset($row[2]) ? $row[2] : '暂无推进数据';
                $res['current'] = isset($row[4]) ? $row[4] : '暂无当前情况';
                $res['xintai']  = isset($row[6]) ? $row[6] : '暂无统计数据';
                # bad: 解决方案. good: 加速方案
                $res['solution'] = isset($row[8]) ? $row[8] : '暂无统计数据';
                # 新增: 时间节点预测
                $res['predict'] = isset($row[10]) ? $row[10] : '暂无统计数据';
                # 双方正在做的事和想法 
                $res['idea']    = isset($row[12]) ? $row[12] : '暂无统计数据';
                # 只需要改这里: 1,2,3
                $res['types']   = 1;
                $res['create_at'] = time();
#                Db::name('docs_copy')->insert($res); 
                Db::name('docs_latest_copy')->insert($res);
            }            
        }

        exit('success');
    }
}
